package com.guli.eduservice.controller;


import com.guli.commonutils.R;
import com.guli.eduservice.client.VodClient;
import com.guli.eduservice.service.EduVideoService;
import com.guli.eduservice.bean.EduVideo;
import com.guli.servicebase.exceptionHandler.GuliException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-04-04
 */
@Api("课程小节管理")
@RestController
@RequestMapping("/eduservice/eduvideo")
@CrossOrigin
public class EduVideoController {
    @Resource
    private EduVideoService eduVideoService;
    @Resource
    private VodClient vodClient;

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    //修改小节
    @PostMapping("updateVideo")
    public R updateChapter(@RequestBody EduVideo eduVideo){
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

    //根据章节id查询小节
    @GetMapping("getVideoById/{id}")
    public R getChapterById(@PathVariable("id")String id){
        EduVideo eduVideo = eduVideoService.getById(id);
        return R.ok().data("eduVideo",eduVideo);
    }

    //删除小节
    @DeleteMapping("deleteChapterById/{id}")
    public R deleteChapterById(@PathVariable("id")String id){
        //1.删除阿里云视频
        EduVideo byId = eduVideoService.getById(id);
        String videoSourceId = byId.getVideoSourceId(); //获取视频id
        if(!StringUtils.isEmpty(videoSourceId)){
            R r = vodClient.removeVideo(videoSourceId);
            if(r.getCode()!=20000){
                throw new GuliException(20001,"删除视频失败，熔断器生效");
            }
        }
        //2.删除小节
        boolean flag = eduVideoService.removeById(id);
        if(flag){
            return R.ok();
        }else{
            return R.error().message("删除失败");
        }

    }
}

